<template>
  <div class="container">
    <div class="navigationBar" style="width: 98%;margin: 10px auto 0">
      <el-row :gutter="24">
        <!-- 搜索框 -->
        <el-col :span="5">
          <el-input v-model="listQuery.name" placeholder="请输入机构名称" clearable @change="search"></el-input>
        </el-col>


        <el-col  :span="16">
          <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-col>

        <el-col :span="3" align="center" class="add" style="display: none">
          <el-button type="success" @click="handleAdd" disabled>新增机构</el-button>
        </el-col>

      </el-row>
    </div>


    <div class="filter-container">
      <el-checkbox v-model="formThead.name" label="机构名称">机构名称</el-checkbox>
      <el-checkbox v-model="formThead.customer_id" label="所属用户">所属用户</el-checkbox>
<!--      <el-checkbox v-model="formThead.province" label="所属省份">所属省份</el-checkbox>-->
<!--      <el-checkbox v-model="formThead.city" label="所属城市">所属城市</el-checkbox>-->
<!--      <el-checkbox v-model="formThead.country" label="所属县/区">所属县/区</el-checkbox>-->
      <el-checkbox v-model="formThead.address" label="详细地址">详细地址</el-checkbox>
      <el-checkbox v-model="formThead.contact" label="联系人">联系人</el-checkbox>
      <el-checkbox v-model="formThead.telephone" label="联系电话">联系电话</el-checkbox>
      <el-checkbox v-model="formThead.status" label="状态">状态</el-checkbox>
      <el-checkbox v-model="formThead.date_added" label="添加时间">添加时间</el-checkbox>
      <el-checkbox v-model="formThead.salesroom" label="门店信息">门店信息</el-checkbox>

    </div>

    <el-table :data="organizationList" class="table" border :key="organizationList.length"
              v-loading="loading"
              element-loading-text="拼命加载中....">
      <el-table-column label="机构名称" align="center" v-if="formThead.name">
        <template slot-scope="{row}">
          <span>{{row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column label="所属用户" align="center" v-if="formThead.customer_id">
        <template slot-scope="{row}">
          <span>{{getCustomerName(row.customer_id)}}</span>
        </template>
      </el-table-column>

<!--      <el-table-column label="所属省份" align="center" v-if="formThead.province">-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{row.province}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="所属城市" align="center" v-if="formThead.city">-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{row.city}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="所属县/区" align="center" v-if="formThead.country">-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{row.country}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->


      <el-table-column label="详细地址" align="center" v-if="formThead.address">
        <template slot-scope="{row}">
          <span>{{getAddress(row.province, row.city, row.country, row.address)}}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系人" align="center" v-if="formThead.contact">
        <template slot-scope="{row}">
          <span>{{row.contact}}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系电话" align="center" v-if="formThead.telephone">
        <template slot-scope="{row}">
          <span>{{row.telephone}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="tag" label="状态" align="center" v-if="formThead.status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 0 ? 'danger' : 'primary'" disable-transitions>
            {{scope.row.status === 0 ? '禁用':'启用'}}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="添加时间" align="center" v-if="formThead.date_added">
        <template slot-scope="{row}">
          <span>{{row.date_added}}</span>
        </template>
      </el-table-column>

      <!--   门店信息   -->
      <el-table-column label="门店信息" align="center" v-if="formThead.salesroom">
        <template slot-scope="{row}">
          <i class="el-icon-view" @click="showSalesroom(row)"></i>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="openDelete(row.customer_organization_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination :current-page="listQuery.page" :page-sizes="[10,15,20,30,50]" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>


    <add-organization ref="showAddDialog"/>
    <edit-organization ref="showEditDialog"/>
    <salesroom ref="showSalesroomDialog" />


  </div>
</template>

<script>

  import addOrganization from './add'
  import EditOrganization from './edit'
  import salesroom from './salesroom'

  import store from '@/store'
  import {list,del} from '@/api/thk/organization'
  import {list as getCustomerList} from '@/api/thk/customer'
  import {list as getProvinceAndCityList} from '@/api/thk/city'


  export default {

    /**
     *
     address: "龙城街道"
     city: 2
     contact: "小幸运"
     customer_id: 9
     customer_organization_id: 1
     date_added: "2020-04-29 11:07:14"
     date_modified: "2020-04-29 11:07:27"
     name: "小太阳"
     province: 18
     status: 1
     telephone: "13687189454"


     customer_organization_id       id
     customer_id                    用户id
     name                           机构名称
     city                           所属城市
     province                       所属城市
     address                        详细地址
     status                         状态
     contact                        联系人
     telephone                      联系电话
     date_added                     添加日期
     date_modified                  最后修改时间

     */

    name: 'organization',
    components: {
      EditOrganization,
      addOrganization,
      salesroom,
    },
    data() {
      return {
        organizationList: [],

        customerList: [],
        provinceAndCityList: [],
        cityList: [],
        countryList: [],

        formThead: {
          name: true,
          customer_id: true,
          province: true,
          city: true,
          country: true,
          address: true,
          contact: true,
          telephone: true,
          status: true,
          date_added: true,
          salesroom: false,
        },

        listQuery: {
          name: undefined,
          status:undefined,
          page: 1,
          pagesize: 10
        },

        total: undefined,
        loading: true,
      }
    },

    // call api
    created() {
      this.getOrganizationList()
      this.getCustomerList()
      this.getProvinceAndCityList()
    },

    updated: function () {
      this.$nextTick(function () {
        this.loading = false
      })
    },

    methods: {
      // 获取店铺列表
      getOrganizationList(){
        list(store.getters.token, this.listQuery).then(res =>{
          this.total = res.data.list.total
          this.organizationList = res.data.list
          console.log(">>>>>>> organization list =======")
          console.log(this.organizationList)
        },error => {
          console.log(error)
        })
      },

      handleAdd(){
        // 传递，customerList和provinceAndCityList用于选择所属用于和所属城市
        this.$refs.showAddDialog.cancelSubmit(this.customerList,this.provinceAndCityList)
      },

      handleEdit(row){
        this.$refs.showEditDialog.showEditDialog(row,this.customerList,this.provinceAndCityList)
      },

      handleDelete(customer_organization_id){
        del(store.getters.token, customer_organization_id)
        this.getOrganizationList()
      },

      openDelete(customer_organization_id) {
        this.$confirm('此操作将会删除机构, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleDelete(customer_organization_id)
          this.$message({
            type: 'success',
            message: '删除成功!'

          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 搜索功能
      // search(){
      //   this.organizationList = this.tempOrganizationList.filter(organization => {
      //     if (organization.name.search(this.searchText.trim()) !== -1){
      //       return organization
      //     }
      //   })
      // },

      // 搜索功能
      search(){
        this.listQuery.page = 1
        this.getOrganizationList()
      },

      // 获取用户列表
      getCustomerList(){
        getCustomerList(store.getters.token).then(res=>{
          this.customerList = res.data.list.data
        }).then(err => {
          console.log(err)
        })
      },

      // 根据用户id返回用户名,用于显示店铺所属用户
      getCustomerName(customer_id){
        let customers = this.customerList.filter(customer => {
          return customer.customer_id == customer_id
        })

        if(customers[0]){
          return customers[0].nickname
        }

        return ''

      },


      // 获取省市数据
      getProvinceAndCityList(){
        getProvinceAndCityList(store.getters.token).then(res => {
          console.log('===== getProvinceList =====')

          this.provinceAndCityList = res.data.list
          // 获取全部数据的时候,将city的数据筛选出来
          this.getCityList()

          console.log(this.provinceAndCityList)
        }).catch(err => {
          console.log(err)
        })
      },

      // 获取city数据数据
      getCityList(){
        let citys = []
        for(let province of this.provinceAndCityList){
          citys.push(...province.children)
        }

        this.cityList = citys
        this.getCountryList()
      },

      // 遍历获取所有contury中的数据
      getCountryList(){
        let countrys = []
        for(let city of this.cityList){
          countrys.push(...city.children)
        }
        this.countryList = countrys
        console.log(this.countryList)
      },

      // 根据省id返回省名称
      getProvinceName(id){
        let province = this.provinceAndCityList.find(province => {
          return province.province_id === id
        })

        if(province){
          return province.province
        }

        return ''
      },

      // 根据city id返回cityName
      getCityName(id){
        let city = this.cityList.find(city => {
          return id === city.city_id
        })
        if(city){
          return city.city
        }
        return ''
      },

      // 根据country_id返回countryName
      getCountryName(id){
        let country = this.countryList.find(country => {
          return id === country.country_id
        })
        if(country){
          return country.country
        }
        return ''
      },

      getAddress(province, city, country, address){
        let detailedAddress = ""
        if(province !== null && province !== ''){
          detailedAddress += (province+"省")
        }
        return detailedAddress + city + country + address

      },


      handleSizeChange(val) {
        this.listQuery.pagesize = val
        this.getOrganizationList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getOrganizationList()
      },

      showSalesroom(row){
        this.$refs.showSalesroomDialog.showSalesroom(row.customer_organization_id)
      },


    },

  }
</script>

<style scoped>
  .filter-container{
    margin: 10px 0 0 20px;
  }
  .table{
    width: 98%;
    margin: 10px auto 0;
  }
  .add{
    position: relative;
    top: 35px;
  }

  i::before{
    /*display: inline-block;*/
    font-size: 20px;
    height: 18px;
    width: 18px;
  }

  i:hover{
    color: #409EFF;
  }

</style>
